package cn.weekimwee.firstlineofcodeforkotlin.unit3

import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.weekimwee.firstlineofcodeforkotlin.R
import kotlinx.android.synthetic.main.fruit_item.view.*

/**
 * Created by Wee Kim Wee on 2018/2/9.
 */
class FruitAdapter : RecyclerView.Adapter<FruitAdapter.ViewHolder>() {

    /**
     * 没有将data放到构造方法中，而是单独当成一个变量可以更新的，更加方便
     */
    var data: MutableList<Fruit>? = null
        set(value) {
            field = value
            notifyDataSetChanged()
        }
    /**
     * onItemClick的回调  直接用lambda就可以了
     */
    var onItemClick: ((Fruit?) -> Unit)? = null

    /**
     * 创建viewholder 相当于listview中  getView中如果是converView是空的 就创建一个viewholder...
     */
    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
        return ViewHolder(LayoutInflater.from(parent?.context).inflate(R.layout.fruit_item, parent, false))
    }

    override fun getItemCount(): Int {
        return data?.size ?: 0
    }

    /**
     * 绑定viewHolder
     */
    override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
        val fruit = data?.get(position)
        holder?.itemView?.image?.setImageResource(R.mipmap.ic_launcher_round)
        holder?.itemView?.fruit_name?.text = fruit?.name
        holder?.itemView?.setOnClickListener {
            onItemClick?.invoke(fruit)
        }
    }


    class ViewHolder(view: View) : RecyclerView.ViewHolder(view)
}